package com.totoro.springboot.jpa_batch.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Niki on 2018/4/18 10:48
 */
public class AbstractDao<T> implements BatchDao<T> {
    private static final int INTERVAL = 50;
    @PersistenceContext
    protected EntityManager entityManager;


    @Override
    /**
     * 注意该方法需要加上事务注解
     */
    public void batchInsert(List<T> list) {
        int i = 0;
        for (T t : list) {
            entityManager.persist(t);
            i++;
            clear(i,entityManager);
        }

    }

    @Override
    /**
     * 注意该方法需要加上事务注解
     */
    public void batchUpdate(List<T> list) {
        int i = 0;
        for (T t : list) {
            entityManager.merge(t);
            i++;
            clear(i,entityManager);
        }
    }

    private void clear(int index, EntityManager entityManager) {
        if (index % INTERVAL == 0) {
            clear(entityManager);
        }
    }

    private void clear(EntityManager entityManager) {
        entityManager.flush();
        entityManager.flush();
        entityManager.clear();
    }
}
